//This is meeting memo. Please do not use in your application. 
package org.gtug.kobe;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

@SuppressWarnings("serial")
public class SampleServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		req.setAttribute("title", "sample");
		
		long start = System.currentTimeMillis() - 3600 * 1000;
		
		Query query = new Query("Kind");
		query.addFilter("date", FilterOperator.GREATER_THAN_OR_EQUAL, new Date(start));
		query.addSort("date");
		
		DatastoreService service = DatastoreServiceFactory.getDatastoreService();
		PreparedQuery pq = service.prepare(query);
		FetchOptions limit = FetchOptions.Builder.withOffset(0).limit(100);
		List<Entity> result = pq.asList(limit);
		for(int i=0; i<result.size(); i++){
			Entity entityWork = (Entity)result.get(i);
			System.out.println(entityWork.getProperty("message"));
			System.out.println(entityWork.getProperty("date"));
		}
		
		req.setAttribute("Kind", result);
		
        ServletContext context = this.getServletContext();
        RequestDispatcher dispatcher
            = context.getRequestDispatcher("/enter.jsp");
        try {
			dispatcher.forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		System.out.println("version1");
		
		String message = req.getParameter("content");
		System.out.println(message);
		
		Entity entity = new Entity("Kind");
		entity.setProperty("message", message);
		entity.setProperty("date", new Date());
		
		DatastoreService service = DatastoreServiceFactory.getDatastoreService();
		Key key = service.put(entity);
		System.out.println(key);
		
        ServletContext context = this.getServletContext();
        RequestDispatcher dispatcher
            = context.getRequestDispatcher("/html/result.html");
        try {
			dispatcher.forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
